﻿

using AutoMapper;
using CC.Api.Models;
using CC.BLLs;
using CC.Models;
using Microsoft.AspNetCore.Mvc;
using MX.Core.Http.MVC.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;


namespace CC.Api.Controllers
{
    public class ApiController : Controller
    {
        static readonly IMapper mapper;
        static ApiController()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Comment, CommentModel>();
            });
            mapper = config.CreateMapper();
        }


        public ActionResult Index()
        {
            return Content("Comment Server");
        }

        public JsonResult Comment(string context, string outId, long parentId, long memberId)
        {
            MXResult result = new MXResult();
            if (string.IsNullOrEmpty(context))
            {
                result.SetError(9001, "评论内容不能为空");
            }
            else
            if (string.IsNullOrEmpty(outId))
            {
                result.SetError(9002, " 外部Id不能为空");
            }
            else
            {
                outId = parentId > 0 ? $"_inner_comment_{parentId}" : outId;
                var comment = new Comment()
                {
                    CommentId = 0,
                    Context = context,
                    CreateTime = DateTime.Now,
                    FixTop = false,
                    HotVal = 0,
                    LikeCount = 0,
                    MemberId = memberId,
                    OutId = outId,
                    ParentId = parentId,
                    ReplyCount = 0,
                    Type = 0,
                    UpdateTime = DateTime.Now
                };
                comment.CommentId = CommentBLL.Insert(comment);
                if (comment.CommentId < 1)
                {
                    if (string.IsNullOrEmpty(outId))
                    {
                        result.SetError(9003, " 数据写入失败");
                    }
                }
                else
                {
                    Task.Run(() =>
                    {
                        CommentStatisticsBLL.PlusComment(comment.CommentId);
                    });
                    result.Data = new CommentModel
                    {
                        CommentId = comment.CommentId,
                        MemberId = memberId,
                        OutId = outId,
                        ParentId = parentId,
                        Context = context,
                        CreateTime = DateTime.Now,
                    };
                }
            }
            return result.ReturnJson();
        }

        public JsonResult List(string outId = "", long parentId = 0, int pageIndex = 1, long memberId = 0)
        {
            const int pageSize = 20;
            MXResult result = new MXResult();
            if (parentId < 1 && string.IsNullOrEmpty(outId))
            {
                result.SetError(9005, "参数错误");
            }
            else
            {
                var pager = CommentBLL.List(outId, parentId, pageSize, pageIndex);
                var childs = CommentBLL.ChildList(pager.List.Select(cm => cm.CommentId).ToList());
                var outIdList = new List<string>();
                outIdList.Add(outId);
                outIdList.AddRange(pager.List.Select(cm => $"_inner_comment_{cm.CommentId}"));
                var statistics = CommentStatisticsBLL.List(outIdList);
                var memberLikes = memberId > 0 ? LikeBLL.MemberLike(outIdList, memberId) : new List<string>();
                var itemStatis = statistics.Where(s => s.OutId == outId).FirstOrDefault();
                var resultPager = pager.Copy<CommentModel>((Comment cm) =>
                {
                    var statis = statistics.Where(s => s.OutId == $"_inner_comment_{cm.CommentId}").FirstOrDefault();
                    var like = memberLikes.Where(s => s == $"_inner_comment_{cm.CommentId}").FirstOrDefault();
                    var model = mapper.Map<CommentModel>(cm);
                    model.ReplyList = childs.Where(c => c.ParentId == cm.CommentId).Select(c => mapper.Map<CommentModel>(c)).ToList();
                    model.LikeCount = statis == null ? 0 : statis.LikeCount;
                    model.ReplyCount = statis == null ? 0 : statis.CommentCount;
                    model.MyLike = like != null;
                    return model;
                });
                result.ReturnJson(new
                {
                    pager = resultPager,
                    statistics = new CommentStatisticsModel()
                    {
                        CommentCount = itemStatis == null ? 0 : itemStatis.CommentCount,
                        LikeCount = itemStatis == null ? 0 : itemStatis.LikeCount,
                        OutId = outId,
                        DirectCommentCount = itemStatis == null ? 0 : itemStatis.DirectCommentCount,
                        MyLike = memberLikes.Any(s => s == outId)
                    }
                });
            }

            return result.ReturnJson();
        }

        public JsonResult Like(string outId, long memberId)
        {
            MXResult result = new MXResult();
            if (string.IsNullOrEmpty(outId))
            {
                result.SetError(9002, " 外部Id不能为空");
            }
            else
            {
                if (!LikeBLL.Has(outId, memberId))
                {
                    if (!LikeBLL.Like(outId, memberId))
                    {

                        result.SetError(9003, " 数据写入失败");

                    }
                    else
                    {
                        Task.Run(() =>
                        {
                            CommentStatisticsBLL.PlusLike(outId);
                        });
                    }
                }
            }
            return result.ReturnJson();
        }


        public JsonResult UnLike(string outId, long memberId)
        {
            MXResult result = new MXResult();
            if (string.IsNullOrEmpty(outId))
            {
                result.SetError(9002, " 外部Id不能为空");
            }
            else
            {
                if (LikeBLL.Has(outId, memberId))
                {
                    if (!LikeBLL.UnLike(outId, memberId))
                    {

                        result.SetError(9003, " 数据写入失败");

                    }
                    else
                    {
                        Task.Run(() =>
                        {
                            CommentStatisticsBLL.SubLike(outId);
                        });
                    }
                }
            }
            return result.ReturnJson();
        }

        public JsonResult MemberLike(string outIdList, long memberId)
        {
            MXResult result = new MXResult();
            if (string.IsNullOrEmpty(outIdList))
            {
                result.SetError(9002, " 外部Id不能为空");
            }
            else
            {
                var outIds = outIdList.Split(',').ToList();
                result.ReturnJson(LikeBLL.MemberLike(outIds, memberId));
            }
            return result.ReturnJson();


        }
    }
}